const express = require("express");
const exApp = require("../index");
const router = express.Router();
const mysql = require("../connect/pomsql");
const send_email = require("./ownCode.js");
// 加密
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;
const salt = bcrypt.genSaltSync(SALT_WORK_FACTOR);
// token
var jwt = require("jsonwebtoken");
var secretkey = "secretkey";
// 密码解密
let compare = (myPlaintextPassword, hash) => {
  return new Promise((resolve, reject) => {
    bcrypt.compare(myPlaintextPassword, hash, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};
// 验证码
var rel_code = null;
// 发送验证码接口
router.get("/code", async (req, res) => {
  var email = req.query.email;
  rel_code = await createSixNum(); // 随机生成六位数
  var time = new Date().getTime();
  let sql = `SELECT * from users where email = '${email}' `;
  let data = await mysql(sql);
  if (data.length) {
    // 存在
    res.send({
      code: 500,
      msg: "邮箱已注册",
      icon: "fail",
    });
  } else {
    var mail = {
      // 发件人
      from: `"同窗易购"<joy_ysr@qq.com>`,
      // 主题
      subject: "验证码", //邮箱主题
      // 收件人
      to: email, //前台传过来的邮箱
      // 邮件内容，HTML格式
      text: "验证码为：" + rel_code, //发送验证码
    };
    // Initcode = code;
    send_email(mail);
    res.send({
      code: 200,
      msg: "发送成功",
      icon: "success",
    });
  }
});
// 注册
function Fun() {
  var date = new Date();
  return date.toISOString().slice(0, 19).replace("T", " ");
}
router.post("/register", async (req, res) => {
  let { email, password, code } = req.body;
  let create_time = Fun();
  let user = `SELECT * from users where email = '${email}'`;
  let userData = await mysql(user);
  var hash = bcrypt.hashSync(password, salt);
  password = hash;
  let name = email;
  let list = [
    "http://localhost:8888/uploads/wcy.jpg",
    "http://localhost:8888/uploads/tx.jpg",
    "http://localhost:8888/uploads/xrz.gif",
    "http://localhost:8888/uploads/xg.jpg",
    "http://localhost:8888/uploads/txx.jpg",
    "http://localhost:8888/uploads/QQ图片20210824165555.jpg",
    "http://localhost:8888/uploads/cy.jpg",
  ];
  let tx = list[Math.floor(Math.random() * list.length)];
  if (userData.length) {
    res.json({ code: 500, msg: "邮箱已存在，请登录", icon: "fail" });
  } else {
    if (code != rel_code) {
      return res.json({ code: 500, msg: "验证码错误", icon: "fail" });
    } else {
      let sql = `insert into users (email,password,create_time,name,tx) values('${email}','${password}','${create_time}','${name}','${tx}')`;
      let data = await mysql(sql);
      res.json({ code: 200, data, msg: "注册成功", icon: "success" });
    }
  }
});
// 随机六位数
function createSixNum() {
  var Num = "";
  for (var i = 0; i < 6; i++) {
    Num += Math.floor(Math.random() * 10);
  }
  return Num;
}
// 登录
router.post("/login", async function (req, res) {
  let { email, password, code, type } = req.body;
  var token = jwt.sign({ email }, secretkey, { expiresIn: 60 * 8 });
  let user = `SELECT * from users where email = '${email}'`;
  let data = await mysql(user);
  if (data.length) {
    if (type == "code") {
      var isTrue = code == send_email;
    } else {
      var isTrue = await compare(password, data[0].password);
    }
    // let sql_user_data = `UPDATE users SET token = '${token}' where email = '${data[0].email}' `;
    // let add_data_user = await mysql(sql_user_data);
    if (isTrue) {
      res.json({ code: 200, msg: "登录成功", token, data, icon: "success" });
    } else {
      res.json({ code: 500, msg: "邮箱或密码错误", icon: "fail" });
    }
  } else {
    res.json({ code: 500, msg: "邮箱不存在", icon: "fail" });
  }
});
// 固定写法
exApp.use("/", router);
